package com.devframe.srtp.util.common;

import java.awt.Graphics2D;
import java.awt.RenderingHints;
import java.awt.geom.AffineTransform;
import java.awt.image.BufferedImage;
import java.awt.image.ColorModel;
import java.awt.image.WritableRaster;
import java.io.File;

import javax.imageio.ImageIO;

import com.devframe.srtp.SRTPConstants;

public class SRTPThumbUtil {

	/**
	 * 根据现有图片路径获取缩略图的路径
	 * @param filePath
	 * @return
	 */
	public static String getThumbImagePath(String filePath){
		int position = filePath.lastIndexOf(".");
		String suffix = filePath.substring(position);
		String thumbPath=filePath.substring(0,position)+SRTPConstants.THUMB_SUFFIX+suffix;
		return thumbPath;
	}
	
	
	/**
	 * 创建缩略图
	 * @param inPutFile
	 * @param outPutFile
	 * @param width
	 * @param height
	 * @throws Exception
	 */
	public  static  void createThumbImage(File inPutFile, File outPutFile, int width, int height) {
		try {
			BufferedImage source = ImageIO.read(inPutFile);
			if (source == null) {
				return;
			}
			if(source.getWidth()/source.getHeight()>= width/height){             
				if(source.getWidth()>width){                  
					height=(source.getHeight()*width)/source.getWidth();             
				}else{                 
					width=source.getWidth();                 
					height=source.getHeight();             
				}         
			} else{             
				if(source.getHeight()>height){                               
					width=(source.getWidth()*height)/source.getHeight();             
				}else{                 
					width=source.getWidth();                 
					height=source.getHeight();             
				}         
			}     
			double hx = (double)height / source.getHeight();
			double wy = (double)width / source.getWidth();
			if (hx <= wy) {
				wy = hx;
				width = (int)(source.getWidth() * wy);
			} else {
				hx = wy;
				height = (int)(source.getHeight() * hx);
			}
	  
			int type = source.getType();
			BufferedImage target = null;
			if (type == BufferedImage.TYPE_CUSTOM) { // handmade
				ColorModel cm = source.getColorModel();
				WritableRaster raster = 
					cm.createCompatibleWritableRaster(width, height);
				boolean alphaPremultiplied = cm.isAlphaPremultiplied();
				target = new BufferedImage(cm, raster, alphaPremultiplied, null);
			} else {
				target = new BufferedImage(width, height, type);
			}
			Graphics2D g = target.createGraphics();
			g.setRenderingHint(RenderingHints.KEY_INTERPOLATION,
					RenderingHints.VALUE_INTERPOLATION_BICUBIC);
			g.drawRenderedImage(source, AffineTransform.getScaleInstance(wy, hx));
			g.dispose();
			ImageIO.write(target, "JPEG", outPutFile);
		} catch (Exception ex) {
			ex.printStackTrace();
		}
	}
}
